package com.skyolder.taskman.ast;

import java.util.Iterator;

import com.skyolder.taskman.Container;
import com.skyolder.taskman.word.Token;
import com.skyolder.taskman.word.TokenType;

public class IF_Branch extends Branch {

	String condition=null;
	Tree tr=null;
	public IF_Branch(Container c) {
		super(c);
	}
	@Override
	public void build(Iterator<Token> it) throws GrammarError, FormatError {
		Token token=it.next();
		if(token==null){
			throw new GrammarError(Token.NULL);
		}
		TokenType tp=token.getTp();
		if(tp!=TokenType.PARAM){
			throw new GrammarError(token);
		}
		condition=token.getWord();
		if(condition==null){
			throw new GrammarError(token);
		}
		tr=AstBuilder.buildFromTokens(it,this.getContainer());
		if(tr==null){
			throw new GrammarError(Token.NULL);
		}
	}

	@Override
	public Object excute() throws RunError {
		if(condition==null){
			throw new RunError(condition);
		}
		Object o=this.getContainer().getVar(condition);
		if(o==null){
			throw new RunError(condition);
		}
		if(!(o instanceof Boolean)){
			throw new RunError(o.toString());
		}
		Boolean boolean1=(Boolean)o;
		if(boolean1){
			return tr.excute();
		}
		return null;
	}

}
